var async = require("async")
var games = require("../../../../config/games.json")
var errorLogger = require("pomelo-logger").getLogger("error-log");
module.exports = function(app) {
	return new GameRemote(app);
}
var local = {}
var GameRemote = function(app) {
	this.app = app
	GameRemote.app = app
	GameRemote.channelService = this.app.get('channelService');
    GameRemote.dbService = this.app.get("dbService")
    if(GameRemote.dbService && GameRemote.dbService.db){
    	GameRemote.db = GameRemote.dbService.db
    }
    GameRemote.lastDate = (new Date()).getTime()
}

//房间列表
GameRemote.roomList = {}
//玩家映射表
GameRemote.userMap = {}
//游戏工厂
var ROOM_FACTORY = {}
for(var i = 0;i < games.length;i++){
	ROOM_FACTORY[games[i]] = "../../../games/"+games[i]+".js"
}
GameRemote.mainUpdate = function() {
	var curTime = (new Date()).getTime()
	var dt = curTime - GameRemote.lastDate
	GameRemote.lastDate = curTime
	for(var i in GameRemote.roomList){
		if(GameRemote.roomList[i] && GameRemote.roomList[i].mainUpdate && typeof(GameRemote.roomList[i].mainUpdate) == "function"){
			GameRemote.roomList[i].mainUpdate(dt)
		}
	}
}
setInterval(GameRemote.mainUpdate,200)
//创建房间
GameRemote.prototype.newRoom = function(params,uid,sid,roomId,cb){
	console.log("rid : "+roomId+"    uid : "+uid)
	if(GameRemote.userMap[uid]){
		cb(false,"玩家已在房间中")
		return
	}
	if(!ROOM_FACTORY[params.gameType]){
		cb(false)
		return
	}
	CREATE_ROOM_CHECK(params.gameType,uid,function(flag,msg) {
		if(flag){
			GameRemote.roomList[roomId] = require(ROOM_FACTORY[params.gameType]).createRoom(roomId,GameRemote.channelService,GameRemote)
			if(GameRemote.roomList[roomId].setBeforeInfo){
				GameRemote.roomList[roomId].setBeforeInfo(params)
			}
			params.playerInfo.ip = params.ip
			GameRemote.roomList[roomId].userJoin(uid,sid,params.playerInfo,function(flag,msg) {
				if(flag){
					GameRemote.userMap[uid] = roomId
					cb(true)
				}else{
					delete GameRemote.roomList[roomId]
					cb(flag,msg)
				}
			})
		}else{
			cb(false,msg)
		}
	})
}
//加入房间
GameRemote.prototype.join = function(params,uid,sid,roomId,cb) {
	console.log("rid : "+roomId+"    uid : "+uid)
	if(GameRemote.userMap[uid]){
		cb(false,"玩家已在房间中")
		return
	}
	JOIN_ROOM_CHECK(params.gameType,uid,function(flag,msg) {
		if(flag){
			params.playerInfo.ip = params.ip
			GameRemote.roomList[roomId].userJoin(uid,sid,params.playerInfo,function(flag,msg) {
				if(flag){
					GameRemote.userMap[uid] = roomId
					cb(true)
				}else{
					cb(flag,msg)
				}
			})
		}else{
			cb(false,msg)
		}
	})
}
//匹配成功加入一组房间
GameRemote.prototype.groupNewRoom = function(params,players,roomId,info,cb){
	if(!ROOM_FACTORY[params.gameType]){
		cb(false)
		return
	}
	GameRemote.roomList[roomId] = require(ROOM_FACTORY[params.gameType]).createRoom(roomId,GameRemote.channelService,GameRemote)
	if(!GameRemote.roomList[roomId]){
		cb(false)
		return
	}
	if(GameRemote.roomList[roomId].setBeforeInfo){
		GameRemote.roomList[roomId].setBeforeInfo(info)
	}
	var tmpflag = true
	for(let i = 0;i < players.length;i++){
		GameRemote.roomList[roomId].userJoin(players[i].uid,players[i].sid,players[i],function(flag,msg) {
			if(!flag){
				tmpflag = false
			}
		})
	}
	if(tmpflag){
		for(let i = 0;i < players.length;i++){
			GameRemote.userMap[players[i].uid] = roomId
		}
		if(GameRemote.roomList[roomId].setLaterInfo){
			GameRemote.roomList[roomId].setLaterInfo(info)
		}
		cb(true)
	}else{
		delete GameRemote.roomList[roomId]
		cb(false)
	}
}
//创建比赛场房间
GameRemote.prototype.groupNewCompetitionRoom = function(params,players,roomId,info,cb){
	console.log("groupNewCompetitionRoom",params,players,roomId,info)
	if(!ROOM_FACTORY[params.gameType]){
		console.log("params.gameType error "+params.gameType)
		errorLogger.info("params.gameType error "+params.gameType)
		cb(false)
		return
	}
	GameRemote.roomList[roomId] = require(ROOM_FACTORY[params.gameType]).createRoom(roomId,GameRemote.channelService,GameRemote)
	if(!GameRemote.roomList[roomId]){
		console.log("GameRemote.roomList[roomId] error",GameRemote.roomList[roomId])
		errorLogger.info("GameRemote.roomList[roomId] error",GameRemote.roomList[roomId])
		cb(false)
		return
	}
	if(GameRemote.roomList[roomId].setBeforeInfo){
		GameRemote.roomList[roomId].setBeforeInfo(info)
	}
	var tmpflag = true
	for(let i = 0;i < players.length;i++){
		GameRemote.roomList[roomId].userJoin(players[i].uid,players[i].sid,players[i],function(flag,msg) {
			if(!flag){
				errorLogger.info("userJoin cause groupNewCompetitionRoom Fail:"+msg+":"+JSON.stringify(players))
				tmpflag = false
			}
		})
	}
	if(tmpflag){
		for(var i = 0;i < players.length;i++){
			GameRemote.userMap[players[i].uid] = roomId
		}
		if(GameRemote.roomList[roomId].setLaterInfo){
			GameRemote.roomList[roomId].setLaterInfo(info)
		}
		cb(true)
	}else{
		delete GameRemote.roomList[roomId]
		errorLogger.info("userJoin cause groupNewCompetitionRoom Fail")
		cb(false)
	}
}
//房间指令
GameRemote.prototype.receive = function(params,uid,sid,roomId,code,cb) {
	if(GameRemote.roomList[roomId] && GameRemote.roomList[roomId].handle[code]){
		GameRemote.roomList[roomId].handle[code].call(GameRemote.roomList[roomId],parseInt(uid),sid,params,cb)
	}else{
		cb(false)
	}
}
//获取房间信息
GameRemote.prototype.getRoomInfo = function(params,roomId,cb) {
	if(GameRemote.roomList[roomId] && GameRemote.roomList[roomId].handle){
		GameRemote.roomList[roomId].handle.getRoomInfo(0,0,{},cb)
	}
}
//清除过期房间
GameRemote.prototype.clearRoom = function(params,cb) {
	var curTime = (new Date()).getTime()
	for(var roomId in GameRemote.roomList){
		if(GameRemote.roomList[roomId] 
			&& GameRemote.roomList[roomId].roomMode == "hunanRunQuicklyRoom"
			&& curTime - GameRemote.roomList[roomId].createTime > 2 * 60 * 60 * 1000){
			console.log("清除过期房间 : "+roomId)
			GameRemote.roomList[roomId].gameOver()
		}
	}
	cb()
}
//房间结束
GameRemote.gameOver = function(roomId,players,info) {
	//清除状态
	for(var i = 0;i < players.length;i++){
		delete GameRemote.userMap[players[i]]
	}
	GameRemote.app.rpc.game.remote.gameOver(null,roomId,info,function(){})
	delete GameRemote.roomList[roomId]
}
//玩家掉线
GameRemote.prototype.disconnect = function(params,uid,sid,roomId,cb) {
	if(GameRemote.roomList[roomId]){
		GameRemote.roomList[roomId].disconnect(uid)
	}
	cb(true)
}
//玩家重连
GameRemote.prototype.reconnection = function(params,uid,sid,roomId,cb) {
	if(GameRemote.roomList[roomId]){
		GameRemote.roomList[roomId].reconnection(uid,sid)
	}
	cb(true)
}
//玩家退出
GameRemote.userQuit = function(uid,roomId) {
	delete GameRemote.userMap[uid]
	GameRemote.app.rpc.game.remote.userQuit(null,uid,roomId,function(){})
}
//答题游戏进入前检查
local.answerBeforeFun = function(uid,cb) {
	//今日已进行过游戏不能再次参与
	GameRemote.dbService.db.hget("game:answer:playCount",uid,function(err,data) {
		if(err || !data){
			cb(true)
		}else{
			cb(false,"今日已进行过游戏不能再次参与")
		}
	})
}
//创建房间前检查
var CREATE_ROOM_CHECK = function(gameType,uid,cb) {
	switch(gameType){
		case "answer" :
			local.answerBeforeFun(uid,cb)
		break
		case "UNORoom":
			cb(true)
		break
		case "hunanRunQuicklyRoom":
			cb(true)
		break
		default :
			cb(true)
		break
	}
}
//加入游戏前检查
var JOIN_ROOM_CHECK = function(gameType,uid,cb) {
	switch(gameType){
		default :
			cb(true)
		break
	}
}